package com.tom.joke.fragment;

import java.util.List;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


/**
 * 封装代码 FragmentManagerHelper
 * Fragment的管理类
 */
public class FragmentManagerHelper {
    private FragmentManager mFragmentManager; // 管理类
    private int mContainerViewId; // 容器布局 viewId

    public FragmentManagerHelper(@Nullable FragmentManager fragmentManager,
                                 @IdRes int containerViewId) {
        this.mFragmentManager = fragmentManager;
        this.mContainerViewId = containerViewId;
    }

    // 初始化加载Fragment
    public void add(Fragment fragment) {
        FragmentTransaction fTransaction = mFragmentManager.beginTransaction();
        fTransaction.add(mContainerViewId, fragment);
        fTransaction.commit();
    }

    // 切换显示Fragment。
    public void switchFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        // 先隐藏已添加的所有Fragment
        List<Fragment> fragments = mFragmentManager.getFragments();
        for(Fragment f: fragments) {
            fragmentTransaction.hide(f);
        }
        // 2.容器中没有，就添加add；否则显示show。
        if (!fragments.contains(fragment)) {
            fragmentTransaction.add(mContainerViewId, fragment);
        }else {
            fragmentTransaction.show(fragment);
        }
        // fragmentTransaction.replace(R.id.main_tab_fl, mHomeFragment); // 替换Fragment
        fragmentTransaction.commit();
    }

}
